import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/presenter/review_presenter.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/review_details_ui.dart';

import '../../../../http/bean/http_data.dart';
import '../../../../http/bean/worksdo/equipment_management_bean.dart';
import '../../../../http/bean/worksdo/equipment_management_bean.dart';
import '../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../http/model/ajaxsales_model.dart';
import '../../../../http/model/equipment_management_model.dart';
import '../../../dialog/dailog.dart';
import '../../helper/route_helper.dart';
import '../../works/public/image/ui_image_upload.dart';
import 'public/items/ui_attachment.dart';
import 'public/acom/ui_ticketcenter_form.dart';
import 'public/items/ui_ticketcenter.dart';
import 'public/items/ui_ticketcenter2.dart';
import 'public/items/ui_ticketcenter3.dart';
import 'public/review_submitted_ticketcenter.dart';

///工单中心详情
class TicketCenterDetailsRoute extends StatefulWidget {
  @override
  _State createState() => _State();

  EquipmentInfo? data;

  TicketCenterDetailsRoute(this.data);
}

class _State extends State<TicketCenterDetailsRoute> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    presenter?.data = widget.data;

    ///延迟获取数据
    presenter.GetRepairPersonListWithDelay(context, callback: () {});
  }

  @override
  Widget build(BuildContext context) {
    // print("=====================================================================详情页面刷新");
    return ReviewDetailsUi.build(context, presenter, _body,
        title: AppStrings.of(context).Ticket_center);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    AudioplayersUtils.dispose(); //fixme 关闭音频播放。
  }

  Widget _body(BuildContext context) {
    List<Widget> children = [];
    children.add(UiTicketCenter.build(
      context,
      presenter?.data,
      null,
      setState,
    )); //设备报修
    children.add(UiTicketCenter2.build(
      context,
      presenter?.data,
      null,
      setState,
    )); //二级设备信息
    children.add(UiTicketCenter3.build(
      context,
      presenter?.data,
      null,
      setState,
    )); //三级设备信息
    children.add(UiTicketCenterForm.build(
        context, presenter?.maintenanceManInfos)); //设备工程师名单
    children.add(UiAttachment.build(context, presenter?.data?.getFiles(),
        isDel: false)); //附件
    return Column(
      children: [
        Expanded(child: UiBase.listView(context, children)),
        Visibility(
            child: ReviewSubmittedStateful2(
              presenter?.getEquipmentResponseData(),
              callbackWithT: (subData) {
                //fixme 提交参数数据
              },
              callbackWithBoolResult: () {
                //fixme 提交数据格式验证
                var data = presenter?.getEquipmentResponseData();
                try {
                  if (StringUtils.isEmpty(data?.Hours)) {
                    AppDialog.showDialogWithInfo(context,
                        content: AppStrings.of(context)
                            .Estimatedworkinghours2); //请先填写预估工时
                    return false;
                  } else {
                    //fixme 这里不限制预估工时大小，只要不为空即可。
                    try {
                      double.parse(data?.Hours ?? "0"); //判断能否转成数字类型。
                    } catch (e) {
                      AppDialog.showDialogWithInfo(context,
                          content: AppStrings.of(context)
                              .Estimatedworkinghours5); //请填写正确有效的预估工时
                      return false;
                    }
                    // var Hours = double.parse(data?.Hours ?? "0");
                    // print("预估工时：${Hours}");
                    // if (Hours <= 0) {
                    //   AppDialog.showDialogWithInfo(context,
                    //       content: AppStrings.of(context)
                    //           .Estimatedworkinghours3); //预估工时不能小于0
                    //   return false;
                    // }
                  }
                  var PersonIds = data?.getPersonIds();
                  if (PersonIds == null || PersonIds.length <= 0) {
                    AppDialog.showDialogWithInfo(context,
                        content:
                            AppStrings.of(context).pleaserepairman); //请选择设备工程师
                    return false;
                  }
                } catch (e) {}
                return true;
              },
            ),
            visible: presenter?.data != null)
      ],
    );
  }
}

class _Presenter extends ReviewPresenter {
  //工单信息
  EquipmentInfo? data = null;

  //报修人员
  List<MaintenanceManInfo>? maintenanceManInfos = null;

  //提交数据
  EquipmentResponseData? _equipmentResponseData = null;

  EquipmentResponseData getEquipmentResponseData() {
    if (_equipmentResponseData == null) {
      _equipmentResponseData = EquipmentResponseData();
    }
    _equipmentResponseData?.equipmentInfo = data;
    _equipmentResponseData?.maintenanceManInfos = maintenanceManInfos;
    return _equipmentResponseData!;
  }

  ///获取审核详情数据
  GetRepairPersonList(BuildContext context,
      {ResponseCallbackWithVoid? callback = null}) {
    isLoad = true;
    //报修人员
    EquipmentManagementModel.GetRepairPersonList(context, true,
        onError: (code, error) {
      isLoad = false;
      setStateBody?.call(() {});
      AppDialog.showDialogWithError(context, code, error)?.then((value) {
        AppRouteHelper.pop(context); //网络异常，关闭当前页面
      });
    })?.then((value) {
      isLoad = false;
      if (value.isSuccessForCode()) {
        try {
          maintenanceManInfos = value?.Data;
          setStateBody?.call(() {});
          callback?.call();
        } catch (e) {}
      } else {
        //异常
        AppDialog.showDialogWithInfo(context, content: value.MsgDetail)
            ?.then((value) {
          AppRouteHelper.pop(context); //关闭当前页面
        });
      }
    });
  }

  ///获取审核详情数据[延迟获取，等待页面加载完成]
  GetRepairPersonListWithDelay(BuildContext context,
      {ResponseCallbackWithVoid? callback = null}) {
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      GetRepairPersonList(context, callback: callback);
    });
  }
}
